package mysql

import (
	"gorm.io/gorm"
)

type GoodsZye3 struct {
	gorm.Model
	GoodsTitle  string  `gorm:"type:varchar(30);comment:商品标题;"`
	GoodsPrice  float32 `gorm:"type:decimal(10,2);comment:商品价格;"`
	GoodsStock  int64   `gorm:"type:int(10);comment:商品库存;"`
	GoodsStatus int8    `gorm:"type:tinyint(1);comment:商品状态 1代表上架 0代表下架;"`
	GoodsAvatar string  `gorm:"type:varchar(255);comment:商品图片;"`
}

// 商品列表
func (g *GoodsZye3) GoodsList(keyword string, page, pageSize int) (list []*GoodsZye3, err error) {
	err = DB.Where("good_title", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

// 新增商品
func (g *GoodsZye3) CreateGoods() error {
	return DB.Create(&g).Error
}

// 商品详情
func (g *GoodsZye3) GoodsDetail(goodsId int) error {
	return DB.Where("id", goodsId).First(&g).Error
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
